import React, { useState, useEffect } from 'react';
import { Card, Descriptions, Typography, Space, Tag, Button, Dropdown, MenuProps, Modal, Form, Input, message } from 'antd';
import { FileTextOutlined, DownloadOutlined, EditOutlined, FileExcelOutlined } from '@ant-design/icons';
import { ExperimentFullData, ExperimentUpdate } from '../../types';
import { formatDate } from '../../utils/formatUtils';
import { experimentApi } from '../../services/api';

const { Title, Text } = Typography;

interface ExperimentInfoCardProps {
  experiment: ExperimentFullData;
  projectNameEn: string;
  onViewParameters?: () => void;
  onUpdateExperiment?: (experimentId: number, data: ExperimentUpdate) => Promise<any>;
}

const ExperimentInfoCard: React.FC<ExperimentInfoCardProps> = ({ experiment, projectNameEn, onViewParameters, onUpdateExperiment }) => {
  const [formats, setFormats] = useState<Array<{ format: string; name: string; extensions: string[]; description: string }>>([]);
  const [loadingFormats, setLoadingFormats] = useState(false);
  const [editVisible, setEditVisible] = useState(false);
  const [saving, setSaving] = useState(false);
  const [form] = Form.useForm();

  useEffect(() => {
    // 加载支持的格式列表
    const loadFormats = async () => {
      if (!experiment.snapshot_file_path) {
        return;
      }
      setLoadingFormats(true);
      try {
        const data = await experimentApi.getSnapshotExportFormats(projectNameEn, experiment.id);
        setFormats(data.formats || []);
      } catch (err) {
        console.error('加载格式列表失败:', err);
      } finally {
        setLoadingFormats(false);
      }
    };
    loadFormats();
  }, [projectNameEn, experiment.id, experiment.snapshot_file_path]);

  const handleDownload = (format: string) => {
    experimentApi.downloadExperimentSnapshot(projectNameEn, experiment.id, format);
  };

  const handleExportResults = () => {
    try {
      experimentApi.downloadExperimentResultsExcel(projectNameEn, experiment.id);
      message.success('实验结果Excel导出已开始，若数据量较大请耐心等待。');
    } catch (err) {
      console.error('导出实验结果失败:', err);
      message.error('导出实验结果失败，请稍后重试。');
    }
  };

  const downloadMenuItems: MenuProps['items'] = formats.map(format => ({
    key: format.format,
    label: format.name || format.format,
    onClick: () => handleDownload(format.format),
  }));

  useEffect(() => {
    form.setFieldsValue({
      name: experiment.name || '',
      description: experiment.description || '',
    });
  }, [experiment.id, experiment.name, experiment.description, form]);

  const handleOpenEdit = () => {
    setEditVisible(true);
  };

  const handleCancelEdit = () => {
    setEditVisible(false);
    form.setFieldsValue({
      name: experiment.name || '',
      description: experiment.description || '',
    });
  };

  const handleSaveEdit = async () => {
    if (!onUpdateExperiment) {
      setEditVisible(false);
      return;
    }

    try {
      const values = await form.validateFields();
      const nextName = (values.name ?? '').trim();
      const nextDescriptionRaw = values.description ?? '';
      const nextDescription = typeof nextDescriptionRaw === 'string' ? nextDescriptionRaw.trim() : '';

      const currentName = (experiment.name ?? '').trim();
      const currentDescription = (experiment.description ?? '').trim();

      const payload: ExperimentUpdate = {};
      if (nextName !== currentName) {
        payload.name = nextName;
      }
      if (nextDescription !== currentDescription) {
        payload.description = nextDescription;
      }

      if (Object.keys(payload).length === 0) {
        message.info('未检测到需要保存的修改');
        setEditVisible(false);
        return;
      }

      setSaving(true);
      await onUpdateExperiment(experiment.id, payload);
      message.success('实验信息已更新');
      setEditVisible(false);
    } catch (err: any) {
      if (err?.errorFields) {
        return;
      }
      // 其他错误由外层hook已处理，这里仅保持弹窗打开
    } finally {
      setSaving(false);
    }
  };

  return (
    <Card style={{ marginBottom: 16 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
        <Title level={4} style={{ margin: 0 }}>
          <Space size="middle" align="center">
            <span>{experiment.name || `实验 #${experiment.id}`}</span>
            <Tag 
              color="blue" 
              style={{ 
                fontSize: '13px',
                padding: '2px 10px',
                borderRadius: '12px',
                margin: 0,
                fontWeight: 500,
                lineHeight: '20px'
              }}
            >
              #{experiment.id}
            </Tag>
            <Text type="secondary" style={{ fontSize: '14px', fontWeight: 'normal' }}>
              创建时间: {formatDate(experiment.created_at)}
            </Text>
          </Space>
        </Title>
        <Space>
          {onUpdateExperiment && (
            <Button
              icon={<EditOutlined />}
              size="small"
              onClick={handleOpenEdit}
            >
              编辑信息
            </Button>
          )}
          {onViewParameters && (
            <Button
              type="primary"
              icon={<FileTextOutlined />}
              onClick={onViewParameters}
              size="small"
            >
              查看输入参数
            </Button>
          )}
          {experiment.snapshot_file_path && (
            <Dropdown
              menu={{ items: downloadMenuItems }}
              trigger={['click']}
              disabled={loadingFormats || formats.length === 0}
            >
              <Button
                icon={<DownloadOutlined />}
                size="small"
                loading={loadingFormats}
              >
                下载快照
              </Button>
            </Dropdown>
          )}
          <Button
            icon={<FileExcelOutlined />}
            size="small"
            onClick={handleExportResults}
          >
            导出实验结果
          </Button>
        </Space>
      </div>
      {experiment.description && (
        <Descriptions column={1} size="small">
          <Descriptions.Item label="描述">
            {experiment.description}
          </Descriptions.Item>
        </Descriptions>
      )}
      <Modal
        open={editVisible}
        title="编辑实验信息"
        onCancel={handleCancelEdit}
        onOk={handleSaveEdit}
        confirmLoading={saving}
        destroyOnClose
      >
        <Form form={form} layout="vertical">
          <Form.Item
            label="实验名称"
            name="name"
            rules={[
              { max: 200, message: '名称长度不能超过200个字符' },
            ]}
          >
            <Input placeholder="请输入实验名称" allowClear />
          </Form.Item>
          <Form.Item
            label="实验描述"
            name="description"
            rules={[
              { max: 2000, message: '描述长度不能超过2000个字符' },
            ]}
          >
            <Input.TextArea placeholder="请输入实验描述" allowClear autoSize={{ minRows: 3, maxRows: 6 }} />
          </Form.Item>
        </Form>
      </Modal>
    </Card>
  );
};

export default ExperimentInfoCard;

